package group2assignone.ucm.customer;

import group2assignone.dao.MyDAO;
import group2assignone.func.Authentication;
import group2assignone.model.Customer;
import group2assignone.ucm.UCController;
import group2assignone.ucm.UCStartup;
import group2assignone.view.UITool;
import group2assignone.view.customer.CustomerCreateView;
import group2assignone.view.customer.CustomerWelcomeView;
import javax.swing.JOptionPane;

/**
 *Use Case Controller - allows the user to Create an Account from the main UI
 */
public class UCCustomerRegister implements UCController {

    private Customer customer;
    private boolean ok,  okDAO;
    private int option;
    private Authentication auth;
    private CustomerCreateView view;

    public UCCustomerRegister(CustomerCreateView view) {
        this.view = view;
    }

    /**
     * Use Case: Create Customer Account
     * Pre-Condition: Main UI
     * Post-Condition: UI is updated
     * 1. User selects 'Create Account'
     * 2. System updates UI for account details
     * 3. User inputs new account details
     * 4. System verifies details
     * 5. System creates account
     * 6. System logs in user, updating the UI
     * 4a. - System cannot verify details (incorrect data input)
     *     - System displays error message and prompts user to input correct data
     * 5a. - System cannot create account (connection error)
     *     - System displays error message and prompts user to try again later
     */
    public void run() {
        customer = new Customer();
        auth = new Authentication();

        option = view.confirmCreate();
        if (option == JOptionPane.YES_OPTION) {
            view.upLoad(customer);
            ok = auth.checkCustFields(customer);
            if (ok) {
                MyDAO coms = UCStartup.getInstance().getDAO();
                okDAO = coms.sQLAddCustomer(customer);
                if (okDAO) {
                    view.notifyCreate();
                    CustomerWelcomeView gui = new CustomerWelcomeView(customer);
                    gui.go();
                    view.dispose();
                //log in the new customer
                //update UI to 'logged in' screen
                } else {
                    UITool.displayError("Cannot connect to database at this time. Try again later.", view);
                }
            } else {
                UITool.displayError(auth.getErrorMsg(), view);
            }
        }

    }
}
